<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Forgotpass extends CI_Controller {
	function index(){
		$this->load->library('form_validation');
		$this->load->helper(array('form', 'url'));
		$this->load->model('Usermodel');
		$data['adminInfor'] = $this->Usermodel->getAdminInfo();
		$data['title'] =  "Forgot password";		
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
		if ($this->form_validation->run() == FALSE){
			$this->load->view('forgotpass', $data);
		}else{
			$email = trim($this->input->post('email'));
			$userInfor = $this->Usermodel->checkEmailExisted($email);
			if(!$userInfor){
				$errorArray = array();
				$errorArray[] = "The email you entered does not exist";
				$data['errorArray'] = $errorArray;
			}else{
				
				$newPassword = $this->_genRandomString();
				if($this->Usermodel->updatePassByEmail($email, md5($newPassword))){
					$this->load->library('email');
					$this->email->from('info@e-lizer.com', 'E-lizer');
					$this->email->to($email);
										
					$this->email->subject('E-lizer\'s notification');
					if($userInfor->is_wife){
						$dear = "Mrs";
					}else{
						$dear = "Mr";
					}
					$this->email->message('<html>
												<body>
												<p>Dear '.$dear.' '.$userInfor->first_name.' '.$userInfor->last_name.'</p>
												<p>Your account in E-lizer has been updated:</p>
												<p>Username: '.$userInfor->username.'</p>
												<p>New Password: '.$newPassword.'</p>
												</body>
											</html>');
					
					$this->email->send();
					$data['success'] = true;
				}
			}
			$this->load->view('forgotpass', $data);
		}
	}
	function _genRandomString($length = 10) {
	    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
	    $string = '';    
	
	    for ($p = 0; $p < $length; $p++) {
	        $string .= $characters[mt_rand(0, strlen($characters) - 1)];
	    }
	
	    return $string;
	}
}